package com.kyrie.controller;

import com.alibaba.fastjson.JSON;
import com.kyrie.annotation.TransLog;
import com.kyrie.dto.SqlExecuteDto;
import com.kyrie.system.druid.DatasourceSelectHelper;
import com.kyrie.system.mybatis.service.IDefaultService;
import com.kyrie.utils.GlobalConstants;
import com.kyrie.vo.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 描述: 动态sql执行
 *
 * @author wuxiang
 * @date 2020-04-17 15:55
 */
@Validated
@RestController
public class SqlController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "defaultService")
    private IDefaultService service;

    @TransLog(transCode = "/sql/execute",description = "@动态sql执行接口")
    @RequestMapping(value = "/sql/execute",method = RequestMethod.POST)
    public ResponseBean<String> execute(@Valid @RequestBody SqlExecuteDto sqlExecuteDto) {
        String sql = sqlExecuteDto.getSql();
        // 格式标准，去除换行符
        sql = sql.replaceAll("#br#","");
        String db = sqlExecuteDto.getDb();
        // 切库
        DatasourceSelectHelper.setKey(db);

        // 组装动态sql参数
        Map<String,Object> map = new HashMap<>();
        map.put("sqlstr",sql);
        List<SqlParameter> sqlParameters = new ArrayList<>();
        sqlParameters.add(new SqlParameter("sqlstr", Types.VARCHAR));
        Map<String,Object> returnMap = service.call("SP_EXE_SQL",false,map,sqlParameters);
        logger.info("动态sql执行结果为：{}",returnMap);

        return ResponseBean.success(JSON.toJSONString(returnMap), GlobalConstants.SUCCESS_CODE,"@动态sql执行成功");
    }
}
